<template>
  <div id="bannerConfigAddEdit">
    <el-dialog
      class="about-set"
      :title="isAdd ? `添加banner` : '编辑banner'"
      :visible.sync="dialogData.isShow"
      width="650px"
      top="30px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              show-word-limit
              maxlength="20"
              v-model.trim="ruleForm.name"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model.trim="ruleForm.description"
              placeholder=""
              type="textarea"
              show-word-limit
              maxlength="50"
            ></el-input>
          </el-form-item>
          <el-form-item class="min-margin" label="图片" prop="imgInfo">
            <uploadSingImg
              :imgUrl="ruleForm.imgInfo"
              accept=".jpg,.jpeg,.png,.gif"
              :maxSize="5"
              @getImgUrl="getImgUrl"
            >
              <template v-slot:imgInfo>（图片尺寸为900*318）</template>
            </uploadSingImg>
          </el-form-item>
          <el-form-item class="min-margin" label="频道" prop="channels">
            <el-checkbox
              :indeterminate="isChannelIndeterminate"
              v-model="channelCheckAll"
              @change="handleCheckAllChannel"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group
              v-model="ruleForm.channels"
              @change="handleCheckedChannelChange"
            >
              <el-checkbox
                v-for="(item, index) in channelList"
                :label="item.dictValue"
                :key="index"
                :value="item.dictValue"
                >{{ item.dictLabel }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item class="min-margin" label="显示终端" prop="terminals">
            <el-checkbox
              :indeterminate="isTerminalIndeterminate"
              v-model="terminalCheckAll"
              @change="handleCheckAllTerminalChange"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group
              v-model="ruleForm.terminals"
              @change="handleCheckedTerminalChange"
            >
              <el-checkbox
                v-for="(item, index) in terminalList"
                :label="item.dictValue"
                :key="index"
                >{{ item.dictLabel }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <template v-if="isShowRadioDialog">
            <el-form-item>
              <el-radio
                v-for="item in radioList"
                :key="item.labelValue"
                @change="selectRadio"
                v-model="ruleForm.redirectType"
                :label="item.labelValue"
                >{{ item.labelName }}</el-radio
              >
            </el-form-item>
            <el-form-item
              v-if="ruleForm.redirectType === 'POST_ID'"
              label="类型"
            >
              <el-select v-model="ruleForm.postType" placeholder="">
                <el-option
                  v-for="item in typeList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
          <el-form-item v-if="ruleForm.redirectType === 'XCX'" class="marginB0">
            <span class="red-text"
              >注：小程序配置请按照输入框中json格式进行填写，如有问题请联系开发老师协助</span
            >
          </el-form-item>
          <el-form-item :label="linkLabel" prop="redirectContent">
            <el-input v-model="ruleForm.redirectContent" clearable />
          </el-form-item>
          <el-form-item label="分组人群" prop="groupType">
            <el-radio-group v-model="ruleForm.groupType">
              <el-radio label="ALL">选择全部</el-radio>
              <el-radio label="GROUPING_PEOPLE">选择分组人群</el-radio>
            </el-radio-group>
            <el-button
              v-show="ruleForm.groupType === 'GROUPING_PEOPLE'"
              type="success"
              @click="handleGrouping"
              style="margin-left:10px"
            >
              选择分组
            </el-button>
          </el-form-item>
          <div class="table-box">
            <el-table
              v-loading="loading"
              :data="selectedGroupList"
              v-show="ruleForm.groupType === 'GROUPING_PEOPLE'"
            >
              <el-table-column label="分组名称" prop="name" align="center">
              </el-table-column>
              <el-table-column label="人数" prop="totalNumber" align="center">
              </el-table-column>
              <el-table-column label="计算状态" align="center">
                <template slot-scope="{ row }">
                  <span>
                    {{
                      row.finalCalculationStatus
                        | filterName('calculation_status')
                    }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-form-item label="显示顺序" prop="sort">
            <el-input
              v-model.number="ruleForm.sort"
              placeholder="取值范围为0-99"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
    <groupCrowdDialog
      v-if="groupCrowdDialogData.isShow"
      :groupCrowdDialogData="groupCrowdDialogData"
      @groupEcho="groupEcho"
    />
  </div>
</template>

<script>
import {
  addBanner,
  getBannerDetail,
  editBanner,
  groupDetail
} from '@/api/spaceConfiguration/bannerConfigure' // 接口
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { validateSpecial } from '@utils/validate'
import groupCrowdDialog from './groupCrowdDialog'
export default {
  name: 'DialogAddEdit',
  msg: '配置标签分类-新增/编辑弹窗',
  props: ['dialogData'],
  components: {
    uploadSingImg,
    groupCrowdDialog
  },
  computed: {
    linkLabel() {
      if (!this.isShowRadioDialog) {
        return '详情链接'
      } else {
        let str = ''
        switch (this.ruleForm.redirectType) {
          case 'POST_ID':
            str = '帖子ID'
            break
          case 'URL':
            str = '链接'
            break
          case 'XCX':
            str = 'ID'
            break
          case 'LABEL_ID':
            str = '标签ID'
            break
        }
        return str
      }
    }
  },
  watch: {
    linkLabel(newV, oldV) {
      if (this.firstIn) {
        this.firstIn = false
      } else {
        this.ruleForm.redirectContent = newV === 'ID' ? this.xcxDescription : ''
      }
      this.$refs['ruleForm'].clearValidate('redirectContent')
      if (!this.isShowRadioDialog || this.ruleForm.redirectType == 'URL') {
        this.rules.redirectContent = this.regURL
      }
      let type = this.ruleForm.redirectType
      if (type == 'POST_ID' || type == 'XCX' || type == 'LABEL_ID') {
        this.rules.redirectContent = this.regID
      }
    }
  },
  data() {
    const _this = this
    const valiAppNmae = (rule, value, callback) => {
      if (!validateSpecial(value)) {
        callback(new Error('不能使用特殊字符'))
      } else {
        callback()
      }
    }
    const valiChannel = (rule, value, callback) => {
      if (_this.ruleForm.channels.length === 0) {
        callback(new Error('请选择频道'))
      } else {
        callback()
      }
    }
    const valiTerminal = (rule, value, callback) => {
      if (_this.ruleForm.terminals.length === 0) {
        callback(new Error('请选择终端'))
      } else {
        callback()
      }
    }
    const valiGroup = (rule, value, callback) => {
      if (value === 'GROUPING_PEOPLE' && !this.selectedGroupList.length) {
        callback(new Error('请选择分组人群'))
      } else {
        callback()
      }
    }
    const valiSort = (rule, value, callback) => {
      if (value < 0 || value > 99) {
        callback(new Error('取值范围为0-99'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      postType: [],
      isShowRadioDialog: false,
      // 终端
      terminalCheckAll: false,
      checkedTerminal: [],
      terminalList: [],
      isTerminalIndeterminate: false,
      // 频道
      channelCheckAll: false,
      channelChecked: [],
      channelList: [],
      isChannelIndeterminate: false,
      isAdd: true, // 新增-true,编辑-false
      firstIn: false, //是否第一次进入（控制redirectContent）
      firstInTerminal: false, //是否第一次进入（控制终端单选）
      loading: false,
      radioList: [
        { labelName: '详情链接', labelValue: 'URL' },
        { labelName: '帖子ID', labelValue: 'POST_ID' },
        { labelName: '小程序', labelValue: 'XCX' },
        { labelName: '标签ID', labelValue: 'LABEL_ID' }
      ],
      ruleForm: {
        name: '', // 名称
        description: '', // 描述
        imgInfo: '', // 图片
        channels: [], // 频道
        terminals: [], //终端
        sort: '', // 排序
        redirectType: '', // 跳转类型
        redirectContent: '', // 跳转内容
        postType: '', // 帖子类型
        groupType: 'ALL',
        groupThrong: ''
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
          { validator: valiAppNmae, trigger: 'blur' }
        ],
        imgInfo: [
          { required: true, message: '图片不能为空', trigger: 'change' }
        ],
        channels: [
          { required: true, validator: valiChannel, trigger: 'change' }
        ],
        terminals: [
          { required: true, validator: valiTerminal, trigger: 'change' }
        ],
        sort: [
          { required: true, message: '显示顺序不能为空', trigger: 'blur' },
          { type: 'number', message: '显示顺序必须为数字值' },
          { validator: valiSort, trigger: 'blur' }
        ],
        redirectContent: [],
        groupType: [{ required: true, validator: valiGroup, trigger: 'change' }]
      },
      regURL: [
        { required: true, message: '链接不能为空', trigger: 'blur' },
        {
          pattern:
            '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]',
          message: '请输入正确的详情链接url',
          trigger: 'blur'
        }
      ],
      regID: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
      xcxDescription: '{"appletId":"","appletType":"","appletPath":""}', //小程序提示语
      groupCrowdDialogData: {
        isShow: false
      },
      selectedGroupList: []
    }
  },
  async mounted() {
    this.rules.redirectContent = this.regURL
    this.getStatusList()
    this.isAdd = this.dialogData.id ? false : true
    if (!this.isAdd) {
      // 编辑
      this.id = this.dialogData.id
      this.firstIn = true
      this.firstInTerminal = true
      this.getFormData()
    }
    /* 字典 计算状态 */
    await sysNormalDisable('calculation_status', 'calculation_status')
  },
  methods: {
    selectRadio(val) {
      this.ruleForm.postType = ''
      this.setDefaultValue()
    },
    async getStatusList() {
      // 显示终端
      this.terminalList = await sysNormalDisable('banner_terminal')
      // 显示频道
      this.channelList = await sysNormalDisable('banner_channel')
      // 显示类型
      this.typeList = await sysNormalDisable('banner_type')
      this.setDefaultValue()
    },
    /*设置默认数据*/
    setDefaultValue() {
      this.ruleForm.postType = this.typeList[0].dictValue
    },
    // 频道全选
    handleCheckAllChannel(val) {
      const data = []
      this.channelList.filter((item) => {
        data.push(item.dictValue)
      })
      this.ruleForm.channels = val ? data : []
      this.isChannelIndeterminate = false
    },
    // 频道单选
    handleCheckedChannelChange(value) {
      let checkedCount = value.length
      this.channelCheckAll = checkedCount === this.channelList.length
      this.isChannelIndeterminate =
        checkedCount > 0 && checkedCount < this.channelList.length
    },
    // 终端全选
    handleCheckAllTerminalChange(val) {
      this.ruleForm.redirectType = 'URL'
      this.isShowRadioDialog = false
      const data = []
      this.terminalList.filter((item) => {
        data.push(item.dictValue)
      })
      this.ruleForm.terminals = val ? data : []
      this.isTerminalIndeterminate = false
    },
    // 终端单选
    handleCheckedTerminalChange(value) {
      if (this.firstInTerminal) {
        this.firstInTerminal = false
      } else {
        this.ruleForm.redirectType = 'URL'
      }
      if (
        value.some((item) => {
          return item === 'APP'
        }) &&
        value.length === 1
      ) {
        this.isShowRadioDialog = true
      } else {
        this.isShowRadioDialog = false
        this.ruleForm.postType = ''
      }
      let checkedCount = value.length
      this.terminalCheckAll = checkedCount === this.terminalList.length
      this.isTerminalIndeterminate =
        checkedCount > 0 && checkedCount < this.terminalList.length
    },
    //封面图设置
    getImgUrl(url) {
      this.ruleForm.imgInfo = url
    },
    /* 编辑时获取表单详情 */
    getFormData() {
      getBannerDetail(this.id, (response) => {
        let {
          name,
          description,
          imgInfo,
          channels,
          terminals,
          sort,
          redirectType,
          redirectContent,
          postType,
          groupThrong
        } = response
        if (response.redirectType === 'POST_ID') {
          this.isShowRadioDialog = true
        }
        if (groupThrong) {
          groupDetail([groupThrong], (res) => {
            this.selectedGroupList = res
            this.$refs['ruleForm'].clearValidate()
          })
        }
        const groupType = groupThrong ? 'GROUPING_PEOPLE' : 'ALL'
        this.ruleForm = {
          name,
          description,
          imgInfo,
          channels,
          sort,
          terminals,
          redirectType,
          redirectContent,
          postType,
          groupType,
          groupThrong
        }
        this.handleCheckedChannelChange(channels)
        this.handleCheckedTerminalChange(terminals)
        this.ruleForm.sort = this.dialogData.type === 'copy' ? '' : sort
      })
    },
    /* 选择分组 */
    handleGrouping() {
      this.groupCrowdDialogData.isShow = true
    },
    /* 分组列表 */
    groupEcho(val) {
      this.selectedGroupList = []
      this.selectedGroupList.push(val)
      this.$refs['ruleForm'].clearValidate(['groupType'])
    },
    /* 确认提交 */
    confirmLabel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.ruleForm.groupType === 'ALL') {
            this.ruleForm.groupThrong = ''
          } else {
            this.ruleForm.groupThrong = this.selectedGroupList[0].id
          }
          let obj = { ...this.ruleForm }
          if (obj.redirectType !== 'POST_ID') {
            obj.postType = ''
          }
          if (this.isAdd || this.dialogData.type === 'copy') {
            // 新增
            addBanner(
              obj,
              (response) => {
                this.loading = false
                this.$emit('refresh')
                this.cancelLabel()
              },
              (response) => {
                this.loading = false
                this.$message.warning({
                  message: response.message,
                  type: 'warning'
                })
              }
            )
          } else {
            // 编辑
            editBanner(
              this.id,
              obj,
              (response) => {
                this.loading = false
                this.$emit('refresh')
                this.cancelLabel()
              },
              (response) => {
                this.loading = false
                this.$message.warning({
                  message: response.message,
                  type: 'warning'
                })
              }
            )
          }
        } else {
          return false
        }
      })
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.id = null
      this.dialogData.labelCategory = ''
      this.dialogData.isShow = false
    }
  }
}
</script>

<style lang="less">
#bannerConfigAddEdit {
  .el-textarea {
    .el-textarea__inner {
      height: 70px;
      padding-bottom: 18px;
    }
    .el-input__count {
      display: inline-block;
      color: #909399;
      background: #fff;
      position: absolute;
      width: calc(100% - 10px);
      font-size: 12px;
      bottom: 1px;
      right: 1px;
      left: 1px;
      text-align: right;
      line-height: 20px;
    }
  }
  .el-form-item.marginB0 {
    margin-bottom: 0;
  }
  .red-text {
    color: #f00;
  }
}
</style>
